<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';

// 表格数据加载状态
const tableLoading = ref(false);

// 充值记录列表数据
const rechargeList = ref([]);

// 搜索表单
const searchForm = reactive({
  keyword: '',
  status: '',
  rechargeType: '',
  dateRange: []
});

// 分页配置
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
});

// 统计周期选择
const statPeriod = ref('today');

// 充值状态选项
const rechargeStatusOptions = [
  { label: '支付中', value: 'pending' },
  { label: '充值成功', value: 'success' },
  { label: '充值失败', value: 'failed' },
  { label: '已退款', value: 'refunded' }
];

// 充值类型选项
const rechargeTypeOptions = [
  { label: '余额充值', value: 'balance' },
  { label: '会员卡购买', value: 'member_card' },
  { label: '套餐购买', value: 'package' },
  { label: '积分充值', value: 'points' }
];

// 支付方式选项
const paymentMethodOptions = [
  { label: '微信支付', value: 'wechat' },
  { label: '支付宝', value: 'alipay' },
  { label: '银行卡', value: 'card' },
  { label: '现金', value: 'cash' },
  { label: 'POS机', value: 'pos' }
];

// 加载充值记录数据
const loadRechargeData = () => {
  tableLoading.value = true;
  
  // 模拟API请求
  setTimeout(() => {
    // 生成模拟数据
    rechargeList.value = Array.from({ length: 20 }, (_, index) => {
      const id = 'RCH' + (100000 + index).toString();
      const statusIndex = Math.floor(Math.random() * 4);
      const typeIndex = Math.floor(Math.random() * 4);
      const paymentIndex = Math.floor(Math.random() * 5);
      const now = new Date();
      const rechargeTime = new Date(now.getTime() - Math.floor(Math.random() * 30) * 24 * 60 * 60 * 1000);
      
      // 随机金额
      const amount = Math.floor(Math.random() * 1000) + 50;
      const actualAmount = rechargeTypeOptions[typeIndex].value === 'balance' 
        ? amount + Math.floor(Math.random() * 100) // 赠送金额
        : amount;
      
      // 随机会员信息
      const memberName = `会员${Math.floor(Math.random() * 100) + 1}`;
      const memberPhone = `1381234${(Math.floor(Math.random() * 10000)).toString().padStart(4, '0')}`;
      
      return {
        id,
        rechargeNo: id,
        memberName,
        memberPhone,
        amount: amount.toFixed(2),
        actualAmount: actualAmount.toFixed(2),
        rechargeType: rechargeTypeOptions[typeIndex].value,
        rechargeTypeName: rechargeTypeOptions[typeIndex].label,
        status: rechargeStatusOptions[statusIndex].value,
        statusName: rechargeStatusOptions[statusIndex].label,
        paymentMethod: paymentMethodOptions[paymentIndex].value,
        paymentMethodName: paymentMethodOptions[paymentIndex].label,
        rechargeTime: rechargeTime.toLocaleString(),
        operator: Math.random() > 0.5 ? '管理员' : '前台员工' + Math.floor(Math.random() * 5 + 1),
        remark: Math.random() > 0.7 ? `备注信息${index + 1}` : ''
      };
    });
    
    pagination.total = 198; // 模拟总数据量
    tableLoading.value = false;
  }, 1000);
};

// 处理页码变化
const handleCurrentChange = (page) => {
  pagination.currentPage = page;
  loadRechargeData();
};

// 处理每页条数变化
const handleSizeChange = (size) => {
  pagination.pageSize = size;
  pagination.currentPage = 1;
  loadRechargeData();
};

// 处理查询
const handleSearch = () => {
  pagination.currentPage = 1;
  loadRechargeData();
};

// 重置查询条件
const resetSearch = () => {
  searchForm.keyword = '';
  searchForm.status = '';
  searchForm.rechargeType = '';
  searchForm.dateRange = [];
  
  pagination.currentPage = 1;
  loadRechargeData();
};

// 查看充值详情
const viewRechargeDetails = (row) => {
  ElMessage.info(`查看充值详情：${row.rechargeNo}`);
};

// 退款操作
const refundRecharge = (row) => {
  if (row.status !== 'success') {
    ElMessage.warning('只能对充值成功的记录进行退款');
    return;
  }
  
  ElMessageBox.confirm(`确定要退款充值记录"${row.rechargeNo}"吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    ElMessage.success('退款成功');
    row.status = 'refunded';
    row.statusName = '已退款';
  }).catch(() => {});
};

// 人工充值
const manualRecharge = () => {
  ElMessage.info('打开人工充值表单');
};

// 充值套餐管理
const manageRechargePackages = () => {
  ElMessage.info('打开充值套餐管理页面');
};

// 打印小票
const printReceipt = (row) => {
  ElMessage.success(`打印充值小票：${row.rechargeNo}`);
};

// 导出充值记录
const exportRechargeRecords = () => {
  ElMessage.success('充值记录导出成功');
};

// 初始化加载
onMounted(() => {
  loadRechargeData();
});
</script>

<template>
  <div class="recharge-container">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>充值管理</h2>
    </div>
    
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :model="searchForm" inline>
        <el-form-item label="关键词">
          <el-input 
            v-model="searchForm.keyword" 
            placeholder="充值号/会员姓名/手机号"
            clearable
          />
        </el-form-item>
        <el-form-item label="充值状态">
          <el-select v-model="searchForm.status" placeholder="请选择" clearable>
            <el-option 
              v-for="item in rechargeStatusOptions" 
              :key="item.value" 
              :label="item.label" 
              :value="item.value" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="充值类型">
          <el-select v-model="searchForm.rechargeType" placeholder="请选择" clearable>
            <el-option 
              v-for="item in rechargeTypeOptions" 
              :key="item.value" 
              :label="item.label" 
              :value="item.value" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="充值时间">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 表格区域 -->
    <el-card>
      <template #header>
        <div class="card-header">
          <span>充值记录</span>
          <div>
            <el-button type="primary" @click="manualRecharge">
              <el-icon><Plus /></el-icon>
              人工充值
            </el-button>
            <el-button type="warning" @click="manageRechargePackages">
              <el-icon><Setting /></el-icon>
              充值套餐管理
            </el-button>
            <el-button type="success" @click="exportRechargeRecords">
              <el-icon><Download /></el-icon>
              导出记录
            </el-button>
          </div>
        </div>
      </template>
      
      <el-table 
        :data="rechargeList" 
        v-loading="tableLoading" 
        border 
        style="width: 100%"
      >
        <el-table-column prop="rechargeNo" label="充值号" width="100" />
        <el-table-column prop="memberName" label="会员姓名" width="100" />
        <el-table-column prop="memberPhone" label="手机号" width="120" />
        <el-table-column prop="rechargeTypeName" label="充值类型" width="100">
          <template #default="{ row }">
            <el-tag 
              :type="
                row.rechargeType === 'balance' ? 'success' : 
                row.rechargeType === 'member_card' ? 'primary' : 
                row.rechargeType === 'package' ? 'warning' : 'info'
              "
            >
              {{ row.rechargeTypeName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="amount" label="充值金额" width="100">
          <template #default="{ row }">
            ¥{{ row.amount }}
          </template>
        </el-table-column>
        <el-table-column prop="actualAmount" label="实际到账" width="100">
          <template #default="{ row }">
            ¥{{ row.actualAmount }}
          </template>
        </el-table-column>
        <el-table-column prop="paymentMethodName" label="支付方式" width="100" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag 
              :type="
                row.status === 'pending' ? 'warning' : 
                row.status === 'success' ? 'success' : 
                row.status === 'failed' ? 'danger' : 'info'
              "
            >
              {{ row.statusName }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="rechargeTime" label="充值时间" width="160" />
        <el-table-column prop="operator" label="操作员" width="100" />
        <el-table-column label="操作" fixed="right" width="210">
          <template #default="{ row }">
            <el-button 
              size="small" 
              @click="viewRechargeDetails(row)"
            >
              详情
            </el-button>
            <el-button 
              size="small" 
              type="success" 
              @click="printReceipt(row)"
            >
              打印小票
            </el-button>
            <el-button 
              v-if="row.status === 'success'"
              size="small" 
              type="danger" 
              @click="refundRecharge(row)"
            >
              退款
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 充值统计卡片 -->
    <el-card class="stat-card">
      <template #header>
        <div class="card-header">
          <span>充值统计</span>
          <el-radio-group v-model="statPeriod" size="small">
            <el-radio-button label="today">今日</el-radio-button>
            <el-radio-button label="week">本周</el-radio-button>
            <el-radio-button label="month">本月</el-radio-button>
          </el-radio-group>
        </div>
      </template>
      
      <el-row :gutter="20">
        <el-col :span="6">
          <div class="stat-item">
            <div class="stat-title">充值笔数</div>
            <div class="stat-value">165</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-item">
            <div class="stat-title">充值金额</div>
            <div class="stat-value">¥28,536.00</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-item">
            <div class="stat-title">平均充值额</div>
            <div class="stat-value">¥172.95</div>
          </div>
        </el-col>
        <el-col :span="6">
          <div class="stat-item">
            <div class="stat-title">退款金额</div>
            <div class="stat-value">¥1,500.00</div>
          </div>
        </el-col>
      </el-row>
    </el-card>
  </div>
</template>

<style scoped>
.recharge-container {
  padding: 20px;
}
.page-header {
  margin-bottom: 20px;
}
.search-card, .stat-card {
  margin-bottom: 20px;
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.stat-item {
  text-align: center;
  padding: 20px 0;
}
.stat-title {
  font-size: 14px;
  color: #606266;
  margin-bottom: 10px;
}
.stat-value {
  font-size: 22px;
  font-weight: bold;
  color: #409EFF;
}
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style> 
